package com.etooling.framework.controller;

import com.etooling.framework.entity.Employee;
import com.etooling.framework.entity.LoginLog;
import com.etooling.framework.jpa.JpaQueryBuilder;
import com.etooling.framework.jpa.Sorts;
import com.etooling.framework.jpa.Specifications;
import com.etooling.framework.repository.LoginLogRepository;
import com.etooling.framework.svo.ReplyObj;
import com.etooling.framework.utils.VoToPoUtil;
import com.etooling.framework.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping(value = "/admin/loginLog")
@Controller
@EnableAutoConfiguration
public class LoginLogController {
    @Autowired
    LoginLogRepository loginLogRepository;

    @RequestMapping("pageQuery")
    @ResponseBody
    ReplyObj pageQuery(HttpServletRequest request,
                       @RequestParam(defaultValue = "10", required = false, value = "pageSize") int pageSize,
                       @RequestParam(defaultValue = "1", required = false, value = "page") int page,
                       @RequestParam(defaultValue = "", required = false, value = "searchValue") String searchValue
    ) {
        Sort sort = Sort.by(Sort.Direction.DESC, "loginTime");//使用一个序
        //分页
        Pageable pageable = PageRequest.of(page - 1, pageSize, sort);
        List<Predicate> predicates = new ArrayList<>();
        //jpa多条件查询器
        Specification spec = new Specification<Employee>() {
            @Override
            public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (WebUtils.checkStr(searchValue)) {
                    predicates.add(cb.or(
                                    cb.like(root.get("remoteIp"), "%" + searchValue + "%"),
                                    cb.like(root.get("loginId"), "%" + searchValue + "%"),
                                    cb.like(root.get("loginResults"), "%" + searchValue + "%")
                            )
                    );
                }
                Predicate[] p = new Predicate[predicates.size()];
                return query.where(predicates.toArray(p)).getRestriction();
            }
        };
        return WebUtils.flushSuccess(loginLogRepository.findAll(spec, pageable));
    }


    @RequestMapping("newJpaPageQuery")
    @ResponseBody
    ReplyObj newJpaPageQuery(HttpServletRequest request,
                             @RequestParam(defaultValue = "10", required = false, value = "pageSize") int pageSize,
                             @RequestParam(defaultValue = "1", required = false, value = "page") int page,
                             @RequestParam(defaultValue = "", required = false, value = "searchValue") String searchValue,
                             @RequestParam(defaultValue = "", required = false, value = "status") String status
    ) {
        JpaQueryBuilder pb = Specifications.<LoginLog>and();
        if (WebUtils.checkStr(status)) {
            pb.eq("status", status);
        }
        if (WebUtils.checkStr(searchValue)) {
            pb.predicate(Specifications.or()
                    .like("remoteIp", "%" + searchValue + "%")
                    .like("loginId", "%" + searchValue + "%")
                    .like("loginResults", "%" + searchValue + "%")
                    .build());
        }
        Specification<LoginLog> spec = pb.build();
        Sort sort = Sorts.builder()
                .asc("birthday")
                .build();
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        return WebUtils.flushSuccess(loginLogRepository.findAll(spec, pageable));
    }

    @RequestMapping("pageTestSQLOrderBy")
    @ResponseBody
    ReplyObj pageTestSQLOrderBy(HttpServletRequest request,
                                @RequestParam(defaultValue = "10", required = false, value = "pageSize") int pageSize,
                                @RequestParam(defaultValue = "1", required = false, value = "page") int page,
                                @RequestParam(defaultValue = "", required = false, value = "searchValue") String searchValue,
                                @RequestParam(defaultValue = "", required = false, value = "status") String status
    ) {
        JpaQueryBuilder pb = Specifications.<LoginLog>and();
        Sort sort = Sorts.builder()
                .asc("login_time")
                .build();

        Pageable pageable = PageRequest.of(page - 1, pageSize, sort);
        Page<Map<String, Object>> returnList =loginLogRepository.findByOrderBy(pageable);
        return WebUtils.flushSuccess(returnList);
    }

    @RequestMapping("add")
    @ResponseBody
    ReplyObj add(HttpServletRequest request, LoginLog vo
    ) {
        loginLogRepository.save(vo);
        return WebUtils.flushSuccess();
    }

    @RequestMapping("update")
    @ResponseBody
    ReplyObj update(HttpServletRequest request, LoginLog vo
    ) {
        try {
            //vo界面传入的对象，po是数据的对象，有很多时候有些属性页面传过来的东西是不全，或不能修改的，如修改时间，这时就是通过第三个属性，忽略一些属性
            LoginLog po = loginLogRepository.getOne(vo.getId());
            po = (LoginLog) VoToPoUtil.copyProperties(po, vo, new String[]{"company", "roles", "randCode", "pwd", "haveCraft", "createTime"});
            loginLogRepository.save(vo);

            return WebUtils.flushSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        } 
    }

    @RequestMapping("del")
    @ResponseBody
    ReplyObj del(HttpServletRequest request, LoginLog vo
    ) {
        try {
            loginLogRepository.deleteById(vo.getId());
            return WebUtils.flushSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return WebUtils.flushFailure();
        }
    }


}
